/**
 *
 */
package com.xiguaji.tiktok.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.xiguaji.boot.toolkit.DateTimeUtils;
import com.xiguaji.boot.toolkit.JsonUtil;
import com.xiguaji.tiktok.v1.ins.brand.model.CommonBrand;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.Collator;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author y.z
 */
public class Ret {

	/**
	 * 数据获取成功
	 */
	public static String success(String message){
		Map<String, Object> ret = new HashMap<>();
		ret.put("Code",200);
		ret.put("Msg",message);
		return getJson(ret);
	}

	public static String success(String message,Object data){
		Map<String, Object> ret = new HashMap<>();
		ret.put("Code",200);
		ret.put("Msg",message);
		ret.put("Data",data);
		return getJson(ret);
	}

	public static String err(String message){
		Map<String, Object> ret = new HashMap<>();
		ret.put("Code",500);
		ret.put("Msg",message);
		return getJson(ret);
	}


	public static String AwemeErr(String message){
		Map<String, Object> ret = new HashMap<>();
		ret.put("Code",506);
		ret.put("Msg",message);
		return getJson(ret);
	}

	public static String userExpired(){
		Map<String, Object> ret = new HashMap<>();
		ret.put("Code",401);
		ret.put("Msg","Your account has expired. Please login again to continue");
		return getJson(ret);
	}

	public static String userAlready(){
		Map<String, Object> ret = new HashMap<>();
		ret.put("Code",430);
		ret.put("Msg","Your account is already logged in on another computer. If it's not authorized, please change your password in time.");
		return getJson(ret);
	}

	public static String noPermission(){
		Map<String, Object> ret = new HashMap<>();
		ret.put("Code",403);
		ret.put("Msg","当前版本没有权限");
		return getJson(ret);
	}

	public static String noPermission(String message){
		Map<String, Object> ret = new HashMap<>();
		ret.put("Code",403);
		ret.put("Msg",message);
		return getJson(ret);
	}
	public static String tooManyRequest(String message){
		Map<String, Object> ret = new HashMap<>();
		ret.put("Code",413);
		ret.put("Msg",message);
		return getJson(ret);
	}

	public static String pageData(long totalCount,Object data){
		Map<String, Object> ret = new HashMap<String, Object>();
		ret.put("TotalCount",totalCount);
		ret.put("ItemList",data);
		return success("数据获取成功",ret);
	}


	//返回json
	private static String getJson(Object object){
		ObjectMapper mapper = new ObjectMapper();
		SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SimpleModule simpleModule = new SimpleModule();
		simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
		simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
        mapper.setDateFormat(fmt);
        mapper.registerModule(simpleModule);
        String json = null;
        try {
        	json = mapper.writeValueAsString(object);
		} catch (JsonGenerationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        //System.out.println(ss);
		return json;
	}

	public static <T> Map<String, Object> beanToMap(T bean) {
		Map<String, Object> map = new HashMap<>();
		if (bean != null) {
			BeanMap beanMap = BeanMap.create(bean);
			for (Object key : beanMap.keySet()) {
				map.put(key+"", beanMap.get(key));
			}
		}
		return map;
	}

	public static void main(String[] args) throws UnsupportedEncodingException {


		System.out.println(DateUtil.parse("20210422", "yyyyMMdd"));
		System.out.println(DateUtil.beginOfWeek(DateUtil.parse("20210419", "yyyyMMdd")));
		System.out.println(DateUtil.endOfWeek(new Date()));


		CommonBrand commandBrand = new CommonBrand();
		commandBrand.setId(1);

		CommonBrand commandBrand2 = new CommonBrand();
		commandBrand2.setId(1);

		Set<CommonBrand> commonBrands = new HashSet<>();
		commonBrands.add(commandBrand2);
		commonBrands.add(commandBrand);
		commonBrands.stream().distinct().collect(Collectors.toList());
		System.out.println("================"+commonBrands.size());




		System.out.println(DateUtil.beginOfDay(new Date()).getTime()/1000);

		DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MMMM-dd HH:mm:ss",Locale.ENGLISH);
		System.out.println(LocalDateTime.now().format(dateTimeFormatter));

		SimpleDateFormat sdf = new SimpleDateFormat("dd MMMM yyyy",
				Locale.ENGLISH);
		System.out.println(sdf.format(new Date()));



		LocalDateTime localDateTime = new Date().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
		System.out.println(Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant()));


		DateUtil.calendar().getMaximum(Calendar.DAY_OF_MONTH);
		System.out.println(DateUtil.calendar().getMaximum(Calendar.DAY_OF_MONTH));
		long six = LocalDateTime.now().minusMonths(2).atZone(ZoneId.systemDefault()).toEpochSecond();
		Calendar calendar = DateUtil.calendar();
		calendar.setTimeInMillis(six*1000);
		System.out.println(calendar.getTime());
		System.out.println(calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
		System.out.println(DateUtil.calendar(DateUtil.parse(String.valueOf(20200401),"yyyyMMdd")).getActualMaximum(Calendar.DAY_OF_MONTH));



		Calendar c = Calendar.getInstance();
		c.set(Calendar.DAY_OF_MONTH,16);
		Calendar b = ObjectUtil.clone(c);
		b.add(Calendar.DAY_OF_MONTH,-7);
		System.out.println(c.getTime());
		System.out.println(b.getTime());

		System.out.println(DateTimeUtils.second(LocalDateTime.now().minusDays(90)));


		Calendar calendar1 = Calendar.getInstance();
		calendar1.setTimeInMillis((1600905600-60*60*24)*1000l);
		//calendar1.setTimeInMillis(System.currentTimeMillis());
		System.out.println(calendar1.get(Calendar.HOUR_OF_DAY)%2);
		System.out.println(DateUtil.format(calendar1.getTime(),"yyyy-MM-dd HH:mm:ss"));
		System.out.println(1600905600-60*60*24);


		System.out.println(DateUtil.format(DateUtil.offsetHour(DateUtil.beginOfDay(new Date()),1),"yyyy-MM-dd HH:mm:ss"));
		System.out.println(DateUtil.format(DateUtil.offsetDay(DateUtil.beginOfDay(new Date()),1),"yyyy-MM-dd HH:mm:ss"));


		System.out.println(DateTimeUtils.second(LocalDateTime.now().minusDays(2)));

		Long timStamp = DateUtil.beginOfDay(new Date()).getTime();
		LocalDateTime  localDateTime1 = LocalDateTime.ofInstant(Instant.ofEpochMilli(timStamp), ZoneId.systemDefault()).minusDays(3);
		System.out.println(localDateTime1.atZone(ZoneId.systemDefault()).toEpochSecond());
		Calendar calendar2 = Calendar.getInstance();
		calendar2.setTimeInMillis(localDateTime1.atZone(ZoneId.systemDefault()).toEpochSecond()*1000);
		System.out.println(DateUtil.format(calendar2.getTime(),"yyyy-MM-dd HH:mm:ss"));

		/*List<Integer> lists = new ArrayList<>();
		lists.add(1);
		lists.add(2);
		lists.add(3);
		lists.add(4);
		lists.add(5);
		lists.sort((Object o1,Object o2) ->{
			System.out.println(o1);
			System.out.println(o2);
			return 0;
		});
		System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++");
		lists.forEach( l ->{
			System.out.println(l);
		});*/


		String json = "{\"favorite\": true}";
		System.out.println(json);
		json = JsonUtil.parseJson(json);
		System.out.println(json);

		/*MusicResponse musicResponse = JsonUtil.jsonParse(MusicResponse.class, json);
		System.out.println(musicResponse.getFavorite());*/


		/*List<Map<String,Object>> mapList = new ArrayList<>();
		Map<String,Object> a = new HashMap<>();
		a.put("ss",123);
		mapList.add(a);
		Map<String,Object> bs = new HashMap<>();
		bs.put("ss",321);
		mapList.add(bs);

		int ggg = mapList.stream().mapToInt(bb -> (int)bb.get("ss")).sum();
		System.out.println(ggg);
		System.out.println(DateUtil.endOfDay(DateUtil.offsetMonth(new Date(),-2)).getTime()/1000);

		DateTimeFormatter dateTimeFormatter1 = DateTimeFormatter.ofPattern("MMM dd, yyyy", Locale.ENGLISH);
		System.out.println(LocalDateTime.now().format(dateTimeFormatter1));*/

		long m = 3;
		long s = 1;
		System.out.println(((int)((double)s/(double)m*100)/100.0));

		System.out.println(1 << 30);


		// List<String> bb = Collections.emptyList();
		List<String> bb = new ArrayList<>(2);
		bb.add("1");
		bb.add("2");
		bb.add("3");
		bb.add("4");
		bb.add("5");
		Map<String,Object> ret = new HashMap<>();
		ret.put("sb","sb");
		ret.put("yyyy",bb);
		System.out.println(JsonUtil.parseJson(ret));

		String [] lists = new String [] {"csssd","abcgs","bsdf","esssd","dsssd"};
		Arrays.sort(lists, Collator.getInstance(Locale.ENGLISH));
		for (String list : lists) {
			System.out.println(list);
		}

		Map<String,String> params = new HashMap<>();
		params.put("ProductId","25");
		params.put("OrderNo", "GUGEE-5-12181018255106334211");
		params.put("Name", "果集支付中心APP支付测试");
		params.put("TotalFee", "100");
		params.put("PayType", "2");
		params.put("ClientIP", "172.26.11.67");
		params.put("Content", "支付内容");
		params.put("Remarks", "");
		params.put("SignKey","71053DE5C4284E8183A2A3A09E627B65");
		String data = createSign(params,false);

		System.out.println(DigestUtils.md5Hex(data));
		System.out.println(org.springframework.util.DigestUtils.md5DigestAsHex(data.getBytes()));
		System.out.println(Math.abs(-2));

		String ss = "ABCDESD";

	}

	/**
	 * 构造签名
	 * @param params
	 * @param encode
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String createSign(Map<String, String> params, boolean encode) throws UnsupportedEncodingException {
		Set<String> keysSet = params.keySet();
		Object[] keys = keysSet.toArray();
		Arrays.sort(keys);
		StringBuffer temp = new StringBuffer();
		boolean first = true;
		for (Object key : keys) {
			Object value = params.get(key);
			if(StringUtils.isEmpty(value)){
				continue;
			}

			if (first) {
				first = false;
			} else {
				temp.append("&");
			}
			temp.append(key).append("=");
			String valueString = "";
			if (null != value) {
				valueString = value.toString();
			}
			if (encode) {
				temp.append(URLEncoder.encode(valueString, "UTF-8"));
			} else {
				temp.append(valueString);
			}
		}
		return temp.toString();
	}



}
